package com.lagou.edu.service.impl;

import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.dao.UserDao;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.pojo.User;
import com.lagou.edu.service.AuthCodeService;
import com.lagou.edu.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author KK
 * @since 2021-09-24
 */
@Service
public class UserServiceImpl implements UserService {


    private final UserDao userDao;
    private final TokenDao tokenDao;

    @Reference(check = false)
    private AuthCodeService authCodeService;


    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;


    public UserServiceImpl(UserDao userDao, TokenDao tokenDao) {
        this.userDao = userDao;
        this.tokenDao = tokenDao;
    }


    @Transactional
    @Override
    public int register(String email, String password, String code, HttpServletResponse response) {

        // 校验验证码
        int validateResult = authCodeService.validate(email, code);
        if (validateResult == 1){
            // 错误的处理逻辑
            return 1;
        }

        if (validateResult == 2){
            // 验证码超时失效的处理逻辑
            return 2;
        }

        // 成功， 则将其保存到用户表中
        User user = new User();
        user.setEmail(email);
        user.setPw(password);
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user = userDao.save(user);

        if (user.getId() == null){
            return 1;
        }
        createTokenAndStore(email, response);


        return 0;
    }

    private void createTokenAndStore(String email, HttpServletResponse response) {
        // 将token写入到cookie中
        String token = createToken(email);

        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(3600 * 4);
        cookie.setPath("/");
        response.addCookie(cookie);

        // 将token写入到数据库中

        tokenDao.deleteTokenByEmail(email);

        Token tokenObject = new Token();
        tokenObject.setEmail(email);
        tokenObject.setToken(token);
        tokenDao.save(tokenObject);
    }

    private String createToken(String email) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("email", email);
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }


    @Override
    public boolean isRegistered(String email) {
        // 确定是否注册
        return userDao.existsUserByEmail(email);
    }

    @Transactional
    @Override
    public boolean login(String email, String password,
                         HttpServletResponse response) {

        // 登录
        // 检查用户名和密码是否正确
        User user = userDao.findUserByEmail(email);


        if (password.equals(user.getPw())){
            // 如果正确， 将token写入cookie
            createTokenAndStore(email, response);
            return true;
        }
        return false;
    }

    @Override
    public String info(String token) {
        Token t = tokenDao.findTokenByToken(token);
        return t.getEmail();
    }
}
